<template>
  <div class="wx_callback">
    <h1>正在处理微信授权登录<br />请稍候...</h1>
  </div>
    
</template>
  
  <script setup>
  import { onMounted } from 'vue';
  import { useUserStore } from '../store/user'
  import { getUserInfo } from '../api/user';
  import axios from 'axios';
  import { ElLoading, ElMessage } from 'element-plus';

  const { userState } = useUserStore()
  
  function getQueryParams() {
    const params = {};
    const queryString = window.location.search.slice(1);
    const pairs = queryString.split("&");
    for (let pair of pairs) {
      const [key, value] = pair.split("=");
      params[key] = decodeURIComponent(value || "");
    }

    console.log('params:', params)
    return params;
  }
  
  async function fetchToken(code) {
    try {
      // 把 code 发给后端
      const response = await axios.post("https://www.gzrbxmt.com/api/wechat/callback", {
        code,
        scope:'snsapi_login'
      },{
        timeout: 10000
      });

      const result = response.data;
      const loginData = { data: result };
      window.parent.postMessage(loginData, 'https://www.gzrbxmt.com');

    } catch (error) {

      console.error("请求出错：", error);
      alert('请求超时，请再试');
      const errorData = { data: 'timeout' }
      window.parent.postMessage(errorData, 'https://www.gzrbxmt.com');
    }
  }
  
  onMounted(() => {
    const { code } = getQueryParams();
    console.log('code:', code)
    if (code) {
      fetchToken(code);
    } else {
      alert("未获取到微信授权code，请检查微信配置或 URL！");
    }
  });
  </script>
  
  <style scoped>
  h1 {
    font-size: 14px;
    color: #FFF;
    text-align: center;
    line-height: 30px;
  }
  .wx_callback {
    width: 87%;
    height: 340px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    
  }
  </style>
  